package cn.edu.scau.cmi.ema.service;

import cn.edu.scau.cmi.ema.base.CmiPagination;
import cn.edu.scau.cmi.ema.domain.*;
import cn.edu.scau.cmi.ema.service.base.CmiEmaService;
import cn.edu.scau.cmi.ema.util.CmiSqlUtil;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.Query;
import java.util.*;
@Service("CrawlerfileService")
@Transactional

public class CrawlerfileServiceImpl extends CmiEmaService implements CrawlerfileService {
	public CrawlerfileServiceImpl() {
	}

	@Transactional
	public Crawlerfile saveCrawlerfile(Crawlerfile crawlerfile) {

		if (crawlerfile.getId() == null) {
			Url url = urlDAO.findUrlById(crawlerfile.getUrl().getId());
			Filetype filetype = filetypeDAO.findFiletypeById(crawlerfile.getFiletype().getId());
			Crawlerfilestatus crawlerfilestatus = crawlerfilestatusDAO
					.findCrawlerfilestatusById(crawlerfile.getCrawlerfilestatus().getId());
			Crawlerfilestandard crawlerfilestandard = crawlerfilestandardDAO
					.findCrawlerfilestandardById(crawlerfile.getCrawlerfilestandard().getId());

			Crawlerfile existingCrawlerfile = crawlerfileDAO.findCrawlerfileByPhysicalPrimaryKey(crawlerfile.getName());

			crawlerfile.setUrl(url);
			crawlerfile.setFiletype(filetype);
			crawlerfile.setCrawlerfilestatus(crawlerfilestatus);
			crawlerfile.setCrawlerfilestandard(crawlerfilestandard);

			if (isEquals(crawlerfile, existingCrawlerfile)) {
				return existingCrawlerfile;
			}

			crawlerfile = crawlerfileDAO.store(crawlerfile);
			crawlerfileDAO.flush();

		} else {
			Crawlerfile existingCrawlerfile = crawlerfileDAO.findCrawlerfileByPrimaryKey(crawlerfile.getId());

			crawlerfile = crawlerfileDAO.store(crawlerfile);
			crawlerfileDAO.flush();
		}

		return crawlerfile;
	}

	public void deleteCrawlerfile(Crawlerfile crawlerfile) {
		crawlerfileDAO.remove(crawlerfile);
		crawlerfileDAO.flush();
	}

	@Transactional
	public void deleteCrawlerfiles(Set<Integer> deleteCrawlerfilesId) {
		Query query = crawlerfileDAO.createNamedQuery("deleteCrawlerfilesById", -1, -1);
		query.setParameter(1, deleteCrawlerfilesId);
		query.executeUpdate();
	}

	@Transactional
	public Set<Crawlerfile> loadCrawlerfiles() {
		return crawlerfileDAO.findAllCrawlerfiles();

	}

	@Transactional
	public Set<Crawlerfile> loadReferenceCrawlerfiles(Set<Crawlerfile> crawlerfiles) {
		Iterator<Crawlerfile> crawlerfilesIterator = crawlerfiles.iterator();
		Set<Crawlerfile> referencedCrawlerfiles = new HashSet<>();
		while (crawlerfilesIterator.hasNext()) {
			Crawlerfile currentCrawlerfile = crawlerfilesIterator.next();

		}
		return referencedCrawlerfiles;
	}

	public Set<Crawlerfile> loadCrawlerfilesByIdSet(Set<Integer> crawlerfileIdSet) {

		Iterator<Integer> crawlerfileIdIterator = crawlerfileIdSet.iterator();
		Set<Crawlerfile> crawlerfileSet = new HashSet<>();
		while (crawlerfileIdIterator.hasNext()) {
			Integer id = crawlerfileIdIterator.next();
			Crawlerfile currentCrawlerfile = crawlerfileDAO.findCrawlerfileById(id);
			crawlerfileSet.add(currentCrawlerfile);
		}
		return crawlerfileSet;
	}

	@Transactional
	public List<Crawlerfile> findAllCrawlerfiles(Integer startResult, Integer maxRows) {
		return new java.util.ArrayList<Crawlerfile>(crawlerfileDAO.findAllCrawlerfiles(startResult, maxRows));
	}

	@Transactional
	public Crawlerfile findCrawlerfileByPrimaryKey(Integer id) {
		return crawlerfileDAO.findCrawlerfileByPrimaryKey(id);
	}

	@Transactional
	public Integer countCrawlerfiles() {
		return ((Long) crawlerfileDAO.createQuerySingleResult("select count(o) from Crawlerfile o").getSingleResult())
				.intValue();
	}

	@Transactional
	public Integer countCrawlerfiles(CmiPagination page) {
		String sql = CmiSqlUtil.createCountHql(page, Crawlerfile.class);
		return ((Long) crawlerfileDAO.createQuerySingleResult(sql).getSingleResult()).intValue();
	}

	/**
	 * search for name with ajax
	 *
	 */
	@Transactional
	public Integer countCrawlerfilesByName(String queryName) {
		Query query = crawlerfileDAO.createNamedQuery("countCrawlerfilesByName", -1, -1);
		query.setParameter(1, queryName);
		return new Long((long) query.getSingleResult()).intValue();
	}

	@Transactional
	public Integer countCrawlerfilesByDetachedCriteria(CmiPagination page) {
		DetachedCriteria detachedCriteria = CmiSqlUtil.createDetachedCriteria(page, Crawlerfile.class);
		Session session = (Session) entityManager.getDelegate();
		detachedCriteria.setProjection(Projections.rowCount());
		return new Long((long) detachedCriteria.getExecutableCriteria(session).uniqueResult()).intValue();
	}

	public Map<String, ?> loadCrawlerfileObjectReferencedSet(Crawlerfile crawlerfile) {
		HashMap<String, Object> objectReferencedSetMap = new HashMap<>();
		if (crawlerfile.getUrl() != null) {

			Set<Integer> urlIds = new HashSet<Integer>();
			urlIds.add(crawlerfile.getUrl().getId());
			objectReferencedSetMap.put("urlIds", urlIds);
		}
		if (crawlerfile.getFiletype() != null) {

			Set<Integer> filetypeIds = new HashSet<Integer>();
			filetypeIds.add(crawlerfile.getFiletype().getId());
			objectReferencedSetMap.put("filetypeIds", filetypeIds);
		}
		if (crawlerfile.getCrawlerfilestatus() != null) {

			Set<Integer> crawlerfilestatusIds = new HashSet<Integer>();
			crawlerfilestatusIds.add(crawlerfile.getCrawlerfilestatus().getId());
			objectReferencedSetMap.put("crawlerfilestatusIds", crawlerfilestatusIds);
		}
		if (crawlerfile.getCrawlerfilestandard() != null) {

			Set<Integer> crawlerfilestandardIds = new HashSet<Integer>();
			crawlerfilestandardIds.add(crawlerfile.getCrawlerfilestandard().getId());
			objectReferencedSetMap.put("crawlerfilestandardIds", crawlerfilestandardIds);
		}

		return objectReferencedSetMap;
	}

	public Map<String, ?> loadCrawlerfileClassReferencedSet(Crawlerfile crawlerfile) {
		HashMap<String, Object> classReferencedSetMap = new HashMap<>();
		classReferencedSetMap.put("urls", urlDAO.findAllUrls());
		classReferencedSetMap.put("filetypes", filetypeDAO.findAllFiletypes());
		classReferencedSetMap.put("crawlerfilestatuss", crawlerfilestatusDAO.findAllCrawlerfilestatuss());
		classReferencedSetMap.put("crawlerfilestandards", crawlerfilestandardDAO.findAllCrawlerfilestandards());

		return classReferencedSetMap;
	}

	public boolean isEquals(Crawlerfile crawlerfile, Object obj) {
		if (obj == crawlerfile)
			return true;
		if (!(obj instanceof Crawlerfile))
			return false;
		Crawlerfile comparedCrawlerfile = (Crawlerfile) obj;
		if (!CheckPropertyEqual(crawlerfile.getName(), comparedCrawlerfile.getName())) {
			return false;
		}
		return true;
	}

	public static <T> boolean CheckPropertyEqual(T originProperty, T comparedProperty) {
		// 基本类型经过参数传递后会自动装箱
		String[] className = originProperty.getClass().getName().split("\\.");
		if (className[0].equals("java") && className[1].equals("math")) {
			return ((Comparable) originProperty).compareTo(comparedProperty) == 0 ? true : false;
		} else {
			return originProperty.equals(comparedProperty);
		}
	}
}

